05. Exercise: Define a Class
title
Exercise: Define a Class
Define a Dog
class
Task Description:
Now it is time to create your own class. In this exercise you will be creating a class that represents a dog. Bellow are the steps you will need to take to create your first class.
Task Feedback:
Nice work!
Solution
ND079 C1 L2 A06b Defining A Class Demo
Your code may be a bit different, but it should have the same variables, constructor, and methods, and it should have the toString
method overridden.
Notice the variables have the private
access modifier to ensure they are not directly accessible. While the methods access modifiers are public
.
public class Dog {
private String dogType;
private String dogName;
private String dogColor;
private int dogAge;
public Dog(String dogType, String dogName, String dogColor, int dogAge) {
super();
this.dogType = dogType;
this.dogName = dogName;
this.dogColor = dogColor;
this.dogAge = dogAge;
}
public String getDogType() {
return dogType;
}
public void setDogType(String dogType) {
this.dogType = dogType;
}
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
public String getDogColor() {
return dogColor;
}
public void setDogColor(String dogColor) {
this.dogColor = dogColor;
}
public int getDogAge() {
return dogAge;
}
public void setDogAge(int dogAge) {
this.dogAge = dogAge;
}
@Override
public String toString() {
return "Dog type:" + dogType + " Dog name:" + dogName + " Dog Color:" + dogColor + " Dog age" + dogAge;
}
}